package cn.tedu.charging.device.dao.repository;

import cn.tedu.charging.common.pojo.po.ChargingStationPO;
import cn.tedu.charging.device.dao.mapper.ChargingStationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.domain.geo.GeoLocation;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StationRepository {
    @Autowired
    private ChargingStationMapper chargingStationMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<ChargingStationPO> findAll() {
        //select * from charging_station
        return chargingStationMapper.selectList(null);
    }

    public GeoResults<GeoLocation<Integer>> nearbyStations(Double longitude, Double latitude, Double radius) {
        //1.调用api方法 radius 提供 中心点 和半径 circle 以及 携带选项 withCoord withDist
        Circle circle=new Circle(
                new Point(longitude,latitude),
                new Distance(radius,Metrics.KILOMETERS));
        RedisGeoCommands.GeoRadiusCommandArgs args=
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                        .includeDistance().includeCoordinates();
        //2.调用方法 直接返回
        return redisTemplate.opsForGeo().radius("beijing_stations",circle,args);
    }

    public String getStationNameById(Integer stationId) {
        String stationKey="station:cache:"+stationId;
        ValueOperations<String,ChargingStationPO> opsFor = redisTemplate.opsForValue();
        ChargingStationPO chargingStationPO = opsFor.get(stationKey);
        if (chargingStationPO==null){
            throw new RuntimeException("缓存数据 异常 请检查");
        }
        return chargingStationPO.getStationName();
    }

    public ChargingStationPO getStationById(Integer stationId) {
        //预热处理 不管缓存有没有 直接读取
        String stationKey="station:cache:"+stationId;
        ValueOperations<String,ChargingStationPO> stringOps = redisTemplate.opsForValue();
        return stringOps.get(stationKey);
    }
}
